package com.weishenai.Utils;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.weishenai.Utils.JdbcUtils.getPreparedStatement;
import static com.weishenai.Utils.JdbcUtils.release;


public class ExecSqlUtils {

    //数据的增删改查
    public static int updateInfo(String sql, Object[] params) throws SQLException {
        int affectRow = -1;
        PreparedStatement preparedStatement = getPreparedStatement(sql);
        if (params != null && params.length > 0) {
            for (int i = 0; i < params.length; i++) {
                if (params[i] == null)
                    params[i] = "";
                preparedStatement.setObject(i + 1, params[i]);
            }
        }
        affectRow = preparedStatement.executeUpdate();
        release(preparedStatement);
        return affectRow;
    }

    //数据库的查询,不带参数
    public static List<Map<String, Object>> queryInfo(String sql) throws SQLException {
        List<Map<String, Object>> result = new ArrayList<>();
        ResultSet resultSet = null;
        PreparedStatement preparedStatement = getPreparedStatement(sql);
        resultSet = preparedStatement.executeQuery();
        while (resultSet.next()) {
            Map<String, Object> resultMap = new HashMap<>();
            for (int i = 0; i < resultSet.getMetaData().getColumnCount(); i++) {
                resultMap.put(resultSet.getMetaData().getColumnName(i + 1), resultSet.getObject(i + 1));
            }
            result.add(resultMap);
        }
        release(preparedStatement);
        return result;
    }

    //带参数查询
    public static List<Map<String, Object>> queryInfo(String sql, Object[] params) throws SQLException {
        List<Map<String, Object>> result = new ArrayList<>();
        ResultSet resultSet = null;
        PreparedStatement preparedStatement = getPreparedStatement(sql);
        if (params != null && params.length > 0) {
            for (int i = 0; i < params.length; i++) {
                preparedStatement.setObject(i + 1, params[i]);
            }
        }
        resultSet = preparedStatement.executeQuery();
        while (resultSet.next()) {
            Map<String, Object> resultMap = new HashMap<>();
            for (int i = 0; i < resultSet.getMetaData().getColumnCount(); i++) {
                resultMap.put(resultSet.getMetaData().getColumnName(i + 1), resultSet.getObject(i + 1));
            }
            result.add(resultMap);
        }
        release(null, preparedStatement, resultSet);
        return result;
    }
}
